import { AlertDialog } from './alertDialog.js'
import { CheckList } from './checkList.js';
import { read as readXLSX, utils as xlsxUtils } from './xlsx.mjs';

const appRoot = document.getElementById('app');
const searchInput = document.getElementById('search-input');
const checkList = document.querySelector('check-list');
const currentItem = document.querySelector('.current');
const DataFileType = '.csv,.xls,.xlsx,.ods,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel';

function showSearchBox() {
   appRoot.classList.add('open-search');
};

function hideSearchBox() {
   appRoot.classList.remove('open-search');
   searchInput.value = '';
};

function exportCSVList() {
   let listString = '';
   checkList.headers.forEach((e) => {
      listString += `${e},`;
   });

   listString += '_status';

   checkList.data?.forEach(data => {
      listString += '\n';
      checkList.headers.forEach(key => {
         const value = data[key] ?? ''
         listString += value?.replace(/,/g, '\\,') + ',';
      });
      listString += data?.status ?? CheckList.ITEM_STATUS.DEFAULT;
   });

   return listString;
};

function selectFile(fileType) {
   return new Promise((reslove, reject) => {
      const view = document.createElement('div');
      const input = document.createElement('input');
      if (fileType) input.accept = fileType;
      input.type = 'file';
      view.append(input);

      new AlertDialog()
         .setTitle('选择文件')
         .setPositiveButton('确定', () => {
            if (input.files.length > 0) {
               reslove(input.files);
            } else {
               reject('user not select any file');
            };
         })
         .setNegativeButton('取消')
         .onDismiss(() => {
            reject('cancled')
         })
         .setView(view)
         .show()
   });
};

function readTableFile(file) {
   return new Promise(reslove => {
      const reader = new FileReader();
      reader.onload = (e) => {
         const data = e.target.result;
         const xlsx = readXLSX(data, { type: 'array' });
         reslove(xlsx);
      };
      reader.readAsArrayBuffer(file);
   });
}

function selectSheet(sheets) {
   return new Promise((reslove, reject) => {
      const view = document.createElement('div');
      const msg = document.createElement('span');
      msg.textContent = '当前表格有多个工作簿，请手动选择';
      view.append(msg);
      const select = document.createElement('select');
      sheets.forEach(e => {
         const opt = document.createElement('option');
         opt.textContent = e;
         opt.value = e;
         select.append(opt);
      });
      view.append(select);

      new AlertDialog()
         .setTitle('选择工作簿')
         .setPositiveButton('确定', () => {
            reslove(select.value);
         })
         .setNegativeButton('取消')
         .onDismiss(() => {
            reject('cancled')
         })
         .setView(view)
         .show()
   });
};

function importDataFromFile() {
   return new Promise((reslove, reject) => {
      selectFile(DataFileType)
         .then(e => {
            readTableFile(e[0])
               .then(xlsx => {
                  const sheetNames = xlsx.SheetNames;
                  if (sheetNames.length > 1) {
                     selectSheet(sheetNames)
                        .then(sheet => {
                           reslove(xlsxUtils.sheet_to_csv(xlsx.Sheets[sheet]));
                        })
                        .catch(err => {
                           console.log(err);
                        })
                  } else {
                     reslove(xlsxUtils.sheet_to_csv(xlsx.Sheets[sheetNames[0]]));
                  };
               })
         })
         .catch(err => {
            console.log(err);
         });
   })
}

document.querySelector('header>.search').addEventListener('click', () => {
   if (appRoot.classList.contains('open-search')) {
      hideSearchBox();
   } else {
      showSearchBox();
   };
});

searchInput.addEventListener('input', e => {
   checkList.filter(e.target.value);
});

document.querySelector('.add-item').addEventListener('click', () => {
   const inputsArray = {};
   if (!checkList?.name) {
      new AlertDialog()
         .setMessage('请先设置标题列')
         .setPositiveButton('确定')
         .show();
      return;
   }
   const name = checkList.name;
   const inputContainer = document.createElement('div');
   checkList.headers.forEach(key => {
      const input = document.createElement('input');
      inputsArray[key] = input;
      input.placeholder = key;
      if (key === name) {
         input.value = '名称';
      }
      inputContainer.append(input);
   });

   new AlertDialog()
      .setTitle('添加')
      .setView(inputContainer)
      .setPositiveButton('确定', function () {
         const data = { ...inputsArray }
         if (inputsArray[checkList.name].value === '') {
            new AlertDialog()
               .setMessage(`"${checkList.name}" 不能为空`)
               .setPositiveButton('确定')
               .show();
         } else {
            for (let key in inputsArray) {
               const input = inputsArray[key];
               data[key] = input.value;
            };
            checkList.append(data);
         }
         return true;
      })
      .show();
});

document.querySelector('.edit-list').addEventListener('click', () => {
   const select = document.createElement('select');
   if (checkList.headers.length >= 0) {
      select.disabled = false;
   } else {
      select.disabled = true;
   };
   checkList.headers.forEach((e) => {
      const option = document.createElement('option');
      option.innerText = e;
      option.value = e;
      if (e === checkList.name) {
         option.selected = true;
      };
      select.append(option);
   });

   const listString = exportCSVList();
   const inputContainer = document.createElement('textarea');
   inputContainer.style.height = '420px';
   inputContainer.value = listString;
   const view = document.createElement('div');
   const selectNote = document.createElement('span');
   selectNote.style.fontSize = '0.8em'
   selectNote.textContent = '标题列';
   view.append(inputContainer);
   view.append(selectNote);
   view.append(select);

   const changeListener = () => {
      const headerMatch = inputContainer.value.match(/^.+$/m);
      select.disabled = true;
      if (headerMatch === null) {
         return;
      };
      const header = headerMatch[0]
         ?.replace(/\\,/g, '{comma}')
         .split(',')
         .map(e => e.replace(/\{comma\}/g, ','));
      select.innerHTML = '';

      header.forEach((e, i) => {
         if (e === '_status') {
            return;
         }
         const col = e === '' ? `colum_${i}` : e;
         const option = document.createElement('option');
         option.innerText = col;
         option.value = col;
         if (e === checkList.name) {
            option.selected = true;
         };
         select.append(option);
         select.disabled = false;
      });
   }

   inputContainer.addEventListener('change', changeListener);

   new AlertDialog()
      .setTitle('修改列表')
      .setView(view)
      .setNegativeButton('取消')
      .setPositiveButton('确定', () => {
         const listStr = inputContainer.value.replace(/(^\n$)/gm, '');

         const [header, ...list] = listStr.split('\n').map(e => {
            return e.replace(/\\,/g, '{comma}')
               .split(',')
               .map(e => e.replace(/\{comma\}/g, ','));
         });
         const formatedList = {
            name: select.value,
            data: [],
         }

         const template = {};
         header.forEach(k => {
            template[k] = undefined;
         });

         checkList.headers = new Set(header);
         checkList.headers.delete('_status');
         list.forEach(e => {
            const row = { ...template };
            header.forEach((k, j) => {
               row[k] = e[j];
            });
            formatedList.data.push(row);
         });
         checkList.data = formatedList;
         inputContainer.removeEventListener('change', changeListener);
      })
      .setNeturalButton('从文件导入', function () {
         importDataFromFile()
            .then(list => {
               inputContainer.value = list;
               changeListener();
            })
         return true;
      })
      .setModal(true)
      .show();
});

const setListAlert = new AlertDialog()
   .setMessage('请先设置名单')
   .setDestoryOnDismiss(false)
   .setPositiveButton('确定', function () {
      this.dismiss();
      return true;
   });

document.querySelector('.ok').addEventListener('click', () => {
   if (currentItem.item) {
      currentItem.item.status = CheckList.ITEM_STATUS.OK;
   } else {
      setListAlert.show();
   };
});

document.querySelector('.absent').addEventListener('click', () => {
   if (currentItem.item) {
      currentItem.item.status = CheckList.ITEM_STATUS.ABSENT;
   } else {
      setListAlert.show();
   };
});

document.querySelector('.late').addEventListener('click', () => {
   if (currentItem.item) {
      currentItem.item.status = CheckList.ITEM_STATUS.LATE;
   } else {
      setListAlert.show();
   };
});

currentItem.addEventListener('click', e => {
   if (!checkList.firstItem && checkList.data) {
      const data = checkList.data;
      const late = data?.filter(e => {
         return e.status === CheckList.ITEM_STATUS.LATE;
      });
      const absent = data?.filter(e => {
         return e.status === CheckList.ITEM_STATUS.ABSENT;
      });
      const ok = data.filter(e => {
         return e.status === CheckList.ITEM_STATUS.OK;
      });
      new AlertDialog()
         .setTitle('点名报告')
         .setMessage(`点名完成, 报告如下:
缺席: ${absent.length}
迟到: ${late.length}
正常: ${ok.length}`)
         .setPositiveButton('确定')
         .setNeturalButton('导出详情', () => {
            const csv = exportCSVList().replace(/_status$/m, '状态');
            const blob = new Blob([csv]);
            const url = URL.createObjectURL(blob);
            const downloadAtag = document.createElement('a');
            downloadAtag.href = url;
            downloadAtag.download = `点名详情-${new Date().toLocaleString()}.csv`;
            downloadAtag.click();
            URL.revokeObjectURL(url)
         })
         .show();
   }
});